public class ReverseWords {
    public String reverseWords(String s) {
        String strs[] = s.split(" +");
        StringBuilder builder = new StringBuilder();
        int i = strs.length-1;
        while (i>=0) {
            if(!strs[i].equals("")) builder.append(strs[i]);
            if(i>0 && !strs[i-1].equals("") && !strs[i].equals(""))
            	builder.append(" ");
            i--;
        }
        return builder.toString();
    }
    public static void main(String args[]) {
        String s = "this is a test";
        //String s = "";
        //String s = "1 ";
        //String s = " 1 ";
        ReverseWords rw = new ReverseWords();
        String ret = rw.reverseWords(s);
        System.out.println(ret);
    }
}
